﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using Rabbit.Logic;
using RabbitShop.Code;
using Raven.Imports.Newtonsoft.Json;

namespace RabbitShop.Action
{
    public partial class Logon : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            if (!string.IsNullOrEmpty(postContent))
            {
                try
                {
                    Customer item = JsonConvert.DeserializeObject<Customer>(postContent);
                    Customer result = null;
                    IQueryable<Customer> list = RabbitUse.GetCustomerByName(Db.Store, item.Name);
                    foreach (Customer customer in list)
                    {
                        if (customer.Password == item.Password)
                        {
                            result = customer;
                            break;
                        }
                    }

                    if (result == null)
                    {
                        Response.Write("用户名密码错误");
                    }
                    else
                    {
                        HttpCookie cok = new HttpCookie(Constant.CookieName);
                        cok.Values.Add(Constant.CookieUname, HttpUtility.UrlEncode(result.Name));
                        cok.Values.Add(Constant.CookieUid, result.Id);
                        cok.Values.Add(Constant.CookieCartNo, result.ShopList == null ? "0" : result.ShopList.Count.ToString());
                        if (result.AddressList != null && result.AddressList.Count > 0)
                        {
                            Address address = result.AddressList[result.DefaultAddressIndex];
                            cok.Values.Add(Constant.CookieUprovince, HttpUtility.UrlEncode(address.Province));
                            cok.Values.Add(Constant.CookieUcity, HttpUtility.UrlEncode(address.City));
                            cok.Values.Add(Constant.CookieUregion, HttpUtility.UrlEncode(address.Region));
                        }
                        
                        cok.Expires = DateTime.Now.AddDays(1);
                        Response.AppendCookie(cok);

                        Response.Write("true");
                    }
                    
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }

            }
            else
            {

                Response.Write("false");
            }
        }
    }
}